package org.liulinlin.sejw.flow;

import java.sql.*;
import java.util.List;
import java.util.ArrayList;

import org.liulinlin.sejw.db.*;

import org.osoa.sca.annotations.Destroy;
import org.osoa.sca.annotations.Init;

public class TrackWorkFlowServiceImpl implements TrackWorkFlowService {
	private DBConnectionManager connMgr;
	
	@Init
	public void init() {
		connMgr = DBConnectionManager.getInstance();
	}
	@Destroy
	public void destroy() {
		connMgr.release();
	}
	
	public List<AllocDetails> queryAllocDetails(String commId, int adStatus, String senderName, String shipComName, String scdId) {
		List<AllocDetails> res = new ArrayList<AllocDetails>();
		
		Connection con = connMgr.getConnection("shipping_export");
		if (con == null) {
			System.out.println("TrackWorkFlowService.queryAllocDetails不能获得数据库连接");
			return null;
		}
		
		try {
			Statement stmt = con.createStatement();
			String sql = "select * from AllocDetails";
			boolean where = false;
			String cond = "";
			if (!commId.isEmpty()) {
				if (where) {
					cond = cond + " and " + "Comm_ID = '" + commId + "'";
				} else {
					cond = cond + "Comm_ID = '" + commId + "'";
					where = true;
				}
			}
			if (adStatus != -1) {
				if (where) {
					cond = cond + " and " + "AD_Status = " + adStatus;
				} else {
					cond = cond + "AD_Status = " + adStatus;
					where = true;
				}
			}
			if (where) {
				sql = sql + " where " + cond;
			}
			ResultSet rs = stmt.executeQuery(sql);
		
			while (rs.next()) {
				AllocDetails ad = new AllocDetails(rs.getInt("AD_ID"));
				
				boolean add = true;
				if (!senderName.isEmpty() && ad.getCommission().getSender().getName() != senderName) {
					add = false;
				}
				OrderPlan op = new OrderPlan(ad.getBAFID());
				if (!shipComName.isEmpty() && op.getShipSchedule().getShipInfo().getShipComInfo().getShortTitle() != shipComName) {
					add = false;
				}
				if (!scdId.isEmpty() && op.getShipSchedule().getId() != scdId) {
					add = false;
				}
				
				if (add) {
					res.add(ad);
				}
			}
			
			rs.close();
			stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			//shutdown();
		}
		connMgr.freeConnection("shipping_export", con);
		return res;
	}
}
